package demo.jackson.serialize;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.node.TextNode;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Objects;

import demo.jackson.JacksonInterface;
import demo.jackson.impl.Payload;
import demo.jackson.impl.Payload100;

/**
 *
 */
public class PayloadDeserialize extends StdDeserializer<Payload> {

    private static final long serialVersionUID = 8851541065777997216L;

    protected PayloadDeserialize() {
        this(null);
    }


    protected PayloadDeserialize(Class<Payload> t) {
        super(t);
    }

    @Override
    public Payload deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        TreeNode treeNode = p.getCodec().readTree(p);
        String type = null;
        TreeNode typeNode = treeNode.get("type");
        if (TextNode.class.isAssignableFrom(typeNode.getClass())) {
            type = ((TextNode) Objects.requireNonNull(typeNode, "type标识符不能为空")).textValue();
        }
        Payload payload = new Payload();
        Field[] fields = Payload.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                Class<?> fieldType = field.getType();
                TreeNode node = treeNode.get("payload");
                if (JacksonInterface.class.isAssignableFrom(fieldType)) {
                    if ("Payload100".equalsIgnoreCase(type)) {
                        Payload100 payload100 = node.traverse(p.getCodec()).readValueAs(Payload100.class);
                        field.set(payload, payload100);
                    }
                }

            } catch (IllegalAccessException ignored) {

            }
        }
        return payload;
    }
}
